package top.dugou.dugou_sso_server.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import top.dugou.dugou_sso_server.common.Encryption;
import top.dugou.dugou_sso_server.common.Result;
import top.dugou.dugou_sso_server.entity.OpenIdJson;
import top.dugou.dugou_sso_server.entity.User;
import top.dugou.dugou_sso_server.service.UserService;
import top.dugou.dugou_sso_server.utils.AES;
import top.dugou.dugou_sso_server.utils.HttpUtil;
import top.dugou.dugou_sso_server.utils.RedisUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class WeiXinLoginController {
    protected static final Logger logger = LoggerFactory.getLogger(WeiXinLoginController.class);
    @Resource
    private UserService userService;

    @Resource
    private RedisUtil redisUtil;

    @Value("${weixin.appid}")
    private String appID;
    @Value("${weixin.appsecret}")
    private String appSecret;

    @ApiOperation(value = "用户登录")
    @ApiResponses({
            @ApiResponse(code = 200,message = "登录成功"),
            @ApiResponse(code = 406,message = "验证失败"),
            @ApiResponse(code = 500,message = "登录失败")
    })
    @RequestMapping(value = "/auth/wx/login",method = RequestMethod.POST)
    @ResponseBody
    public Map login(
            @RequestBody   @ApiParam(value = "用户数据",required = true) User user
    ) throws Exception {
        logger.info("加密数据：{}",user.getUsername());
        logger.info("加密算法的初始向量：{}",user.getPassword());
        logger.info("登录code：{}",user.getOpenid());
        logger.info("用户数据：{}",user.toString());
        String result = "";
        try{//请求微信服务器，用code换取openid。HttpUtil是工具类，后面会给出实现，Configure类是小程序配置信息，后面会给出代码
            result = HttpUtil.doGet(
                    "https://api.weixin.qq.com/sns/jscode2session?appid="
                            + this.appID + "&secret="
                            + this.appSecret + "&js_code="
                            + user.getOpenid()
                            + "&grant_type=authorization_code", null);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        ObjectMapper mapper = new ObjectMapper();
        OpenIdJson openIdJson = mapper.readValue(result,OpenIdJson.class);

        // 设置用户openid
        user.setOpenid(openIdJson.getOpenid());

        String phone = AES.wxDecrypt(user.getUsername(),openIdJson.getSession_key(),user.getPassword());

        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,Object> map = objectMapper.readValue(phone, Map.class);

        // 设置用户手机号
        user.setUsername(map.get("phoneNumber").toString());
        user.setPassword("");
        // 查询 该手机号是否存在
        User isExitUser = new User();
        isExitUser.setUsername(map.get("phoneNumber").toString());
        List<User> list = userService.selectByCondition(isExitUser);
        if (list.size() > 0){
            // 该手机号存在 登录
            Map<String,Object> res = new HashMap<>();
            User user1 = list.get(0);
            res.put("userinfo",user1);
            String key = user1.getUsername()+String.valueOf(System.currentTimeMillis());
            try {
                String token =Encryption.md5(key);
                //登录token  存放着在redis一周
                if(redisUtil.set(token,user1.getId(),60*60*24*7)){
                    res.put("token",token);
                    return  Result.<Map<String,Object>>instance("200","登录成功",res).toJsonMap();
                }else{
                    return  Result.instance("500","登录失败").toJsonMap();
                }
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        } else {
            // 该手机号不存在 注册
            user.setCoins(88);
            user.setCreated(new Date());
            user.setUpdate(new Date());
            int res = userService.addUser(user);
            Map<String,Object> resu = new HashMap<>();
            resu.put("userinfo",user);
            String key = user.getUsername()+String.valueOf(System.currentTimeMillis());
            try {
                String token = Encryption.md5(key);
                //登录token  存放着在redis一周
                if(redisUtil.set(token,user.getId(),60*60*24*7)){
                    resu.put("token",token);
                    return  Result.<Map<String,Object>>instance("200","登录成功",resu).toJsonMap();
                }else{
                    return  Result.instance("500","登录失败").toJsonMap();
                }
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        return  Result.instance("500","登录失败").toJsonMap();
    }
}
